import Feature from "../Feature";
import { IPixelPos, IPoint, IRelativePos } from "../../Interface";
import { ClassName, CtrlType } from "@/Constants";
import Line from "./Line";


function getCurPntsOfPoints(pointArr: IPoint[], i: number) {
    const { x: centerX, y: centerY } = pointArr[i - 1]
    const { x: endX, y: endY } = pointArr[i];
    const { x: startX, y: startY } = pointArr[i - 2]
    const [prevX, prevY] = [(startX + centerX) / 2, (startY + centerY) / 2]
    const [nextX, nextY] = [(centerX + endX) / 2, (centerY + endY) / 2];
    return {
        p1: { x: prevX, y: prevY },
        cp: { x: centerX, y: centerY },
        p2: { x: nextX, y: nextY },
    }
}

// 线段元素
class Pen extends Line {

    static freeLineConfig = {  // 自由画笔线条粗细参数配置
        maxWidth: .6,
        minWidth: .08,
        maxSpeed: 1,
        minSpeed: 0.5,
    }

    lineWidthArr: number[] = [];

    constructor(pointArr: IRelativePos[] = []) {
        super(pointArr);
        this.className = ClassName.PEN;
        this.hoverStyle = '#4A7EBA'
        this.strokeStyle = '#60A6F7';
        this.focusStyle = '#3069D1';
        this.ctrlTypes = [CtrlType.WIDTH_CTRL, CtrlType.HEIGHT_CTRL, CtrlType.SIZE_CTRL, CtrlType.ANGLE_CTRL];  // 可用的控制点类型有哪些
    }

    override draw(ctx: CanvasRenderingContext2D, pointArr: IPixelPos[], lineWidth: number, lineDashArr: number[]) {
        this.setStyle(ctx, lineWidth, lineDashArr);
        pointArr.forEach((p, i) => {
            if (i > 1) {
                const { p1, cp, p2 } = getCurPntsOfPoints(pointArr, i)
                ctx.beginPath();
                ctx.moveTo(p1.x, p1.y);
                ctx.quadraticCurveTo(cp.x, cp.y, p2.x, p2.y);
                ctx.lineWidth = Feature.Render.getRatioSize(this.lineWidthArr[i] || this.lineWidthArr[i - 1] || .2);
                ctx.stroke();
            }
        });
        if(this.cbCapture){
            ctx.strokeStyle = "transparent";
            super.draw(ctx, pointArr, lineWidth, lineDashArr); // 为了能选取,需要画第二遍
        }
    }

    override getSvg(pointArr: IPixelPos[] = []) {
        let path = ''
        pointArr.forEach((p, i) => {
            if (i > 1) {
                const { p1, cp, p2 } = getCurPntsOfPoints(pointArr, i)
                const lineWidth2 = this.lineWidthArr[i] * 2 || this.lineWidthArr[i - 1] || .2;
                path += `<path d="M ${p1.x} ${p1.y} Q ${cp.x} ${cp.y} ${p2.x} ${p2.y}" stroke="${this.strokeStyle}" stroke-width="${Feature.Render.getRatioSize(lineWidth2) * .8}" stroke-linecap="${this.lineCap}" stroke-linejoin="${this.lineJoin}" stroke-dasharray="${this.lineDashArr}" stroke-dashoffset="${this.lineDashOffset}" opacity="${this.opacity}"/>`
            }
        })
        return path;
    }
}

export default Pen;